// views/huodongdetail/helppage/index.js
var BASE_URL = getApp().globalData.BASE_URL
var util = require('../../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    current_page: '', //上拉加载更多当前页
    last_page: '', //上拉加载更多最后页
    showflag: false, //控制上拉加载更多的出现和隐藏,
    showfinish: false, //控制没有数据的出现和隐藏
    active: 0,
    ifmessage: true, //是否开启了授权按钮
    num: "", //已经助力人数
    zhuli_user: '',
    zhuli_num: '', //还差几人助力
    huodong: "",
    active_list: '',
    huodongid: '',
    ifzhuli: false,
    kefu: true,
    id: '',
    ifphone: '',
    popshow: false,
    showloading: true,
    huodonglist: '',
    popifshow: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options, "助力页面的初始数据")
    var userinfo = wx.getStorageSync("USER")
    this.setData({
      id: options.id,
      huodongid: options.huodongid
    })
    var _this = this
    wx.request({
      url: `${BASE_URL}/headline/list_data.html?page=1&size=6&zhi=%E6%B4%BB%E5%8A%A8&type=xiaochengxv`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json' //GET方式是这个
      },
      success(res) {
        console.log(res)
        res.data.list.forEach(function (item, index) {
          item.info = JSON.parse(item.info)
          if (item.other_info) {
            item.other_info = ''
          }
          var newDateTime = new Date().getTime() / 1000
          item.shijian = util.formatTime(item.info.shijian)
          if (Math.floor(newDateTime) > item.shijian) {
            item.falg = false
          } else {
            item.falg = true
          }
        })
        _this.setData({
          huodonglist: res.data.list,
          current_page: 1,
          last_page: res.data.last_page,
        })
      }
    })
    wx.request({
      url: `${BASE_URL}/pay/index`,
      method: "POST",
      data: {
        id: _this.data.id,
        type: 'xiaochengxv',
        uid: userinfo.id
      },
      header: {
        'Content-Type': 'application/json' //GET方式是这个
      },
      success(res) {
        console.log(res)
        if (res.data.list.is_paid == 1) {
          _this.setData({
            active: 2,
            kefu: false,
          })
          console.log('助力好了', _this.data.id)
          // wx.redirectTo({
          //   url: `./third/index?id=${_this.data.id}`
          // })
        } else {
          _this.setData({
            active: 1,
          })
        }
        if (res.data.zhuli_num) {
          // _this.setData({
          //   zhuli_num: res.data.huodong.num - res.data.zhuli_num,
          //   ifzhuli: true
          // })
          res.data.list_user.forEach(item => {
            if (item.avatar.length == 37) {
              item.avatar = `${BASE_URL}` + item.avatar
            }
            item.updatetime = util.formatTimeTwo(item.updatetime, 'Y-M-D');
          })
          _this.setData({
            zhuli_user: res.data.list_user,
            num: res.data.zhuli_num,
            ifzhuli: true
          })
          if (res.data.list.is_paid == 1) {
            _this.setData({
              active: 2,
              kefu: false,
            })
            console.log('助力好了', _this.data.id)
            // wx.redirectTo({
            //   url: `./third/index?id=${_this.data.id}`
            // })
          } else {
            _this.setData({
              active: 1,
            })
          }
        }
        res.data.list.time = util.formatTimeTwo(res.data.list.time, 'Y-M-D h:m:s');
        _this.setData({
          active_list: res.data.list,
          huodong: res.data.huodong,
          num: res.data.zhuli_num,
          showloading: false
        })
      }
    })
  },



  //订阅消息
  message: function () {
    wx.getSetting({
      withSubscriptions: true, //  这里设置为true,下面才mainSwitch
      success: function (res) {
        console.log(res)
        console.log(res.subscriptionsSetting)
        // 调起授权界面弹窗
        if (res.subscriptionsSetting.mainSwitch) { // 用户打开了订阅消息总开关
          if (res.subscriptionsSetting.itemSettings != null) { // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
            let moIdState = res.subscriptionsSetting.itemSettings['GN_YE5unWBY4hsW96726WCHz4avKEVxPg4sGKIrNcCE', 'muS1weIb7AG0fT0QkEdnGVx9rJRN3v1vyO03SvY9Y1Q']; // 用户同意的消息模板id
            if (moIdState === 'accept') {
              console.log('接受了消息推送');

            } else if (moIdState === 'reject') {
              console.log("拒绝消息推送");

            } else if (moIdState === 'ban') {
              console.log("已被后台封禁");
            }
          } else {
            // 当用户没有点击 ’总是保持以上选择，不再询问‘  按钮。那每次执到这都会拉起授权弹窗
            wx.showModal({
              title: '提示',
              content: '请授权开通服务通知',
              showCancel: true,
              success: function (ress) {
                if (ress.confirm) {
                  console.log(ress)
                  wx.requestSubscribeMessage({ // 调起消息订阅界面
                    tmplIds: ['muS1weIb7AG0fT0QkEdnGVx9rJRN3v1vyO03SvY9Y1Q', 'GN_YE5unWBY4hsW96726WCHz4avKEVxPg4sGKIrNcCE'],
                    success(res) {
                      console.log('订阅消息 成功 ');
                      console.log(res);
                    },
                    fail(er) {
                      console.log("订阅消息 失败 ");
                      console.log(er);
                    }
                  })
                }
              }
            })
          }
        } else {
          console.log('订阅消息未开启')
        }
      },
      fail: function (error) {
        console.log(error);
      },
    })
  },

  //点击好友助力按钮
  friendhelp: function () {
    wx.getSetting({
      withSubscriptions: true, //  这里设置为true,下面才mainSwitch
      success: function (res) {
        console.log(res)
        console.log(res.subscriptionsSetting)
        // 调起授权界面弹窗
        if (res.subscriptionsSetting.mainSwitch) { // 用户打开了订阅消息总开关
          if (res.subscriptionsSetting.itemSettings != null) { // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
            let moIdState = res.subscriptionsSetting.itemSettings['GN_YE5unWBY4hsW96726WCHz4avKEVxPg4sGKIrNcCE', 'muS1weIb7AG0fT0QkEdnGVx9rJRN3v1vyO03SvY9Y1Q']; // 用户同意的消息模板id
            if (moIdState === 'accept') {
              console.log('接受了消息推送');

            } else if (moIdState === 'reject') {
              console.log("拒绝消息推送");

            } else if (moIdState === 'ban') {
              console.log("已被后台封禁");
            }
          } else {
            wx.requestSubscribeMessage({ // 调起消息订阅界面
              tmplIds: ['muS1weIb7AG0fT0QkEdnGVx9rJRN3v1vyO03SvY9Y1Q', 'GN_YE5unWBY4hsW96726WCHz4avKEVxPg4sGKIrNcCE'],
              success(res) {
                console.log('订阅消息 成功 ');
                console.log(res);
              },
              fail(er) {
                console.log("订阅消息 失败 ");
                console.log(er);
              }
            })
          }
        } else {
          console.log('订阅消息未开启')
        }
      },
      fail: function (error) {
        console.log(error);
      },
    })
  },


  openpop: function () {
    this.setData({
      popshow: true
    })
  },

  onClose: function () {
    this.setData({
      popshow: false
    })
    wx.showToast({
      title: '入群需要先登录',
      icon: 'none',
      duration: 2000
    })
  },






















  ifphone: function () {
    var value = wx.getStorageSync('phoneNumber')
    if (value) {
      return false
    } else {
      return true
    }
  },

  getcode: function () {
    wx.login({
      success: res => {
        wx.request({
          url: `${BASE_URL}/ajax/login`,
          data: {
            code: res.code
          },
          method: "GET",
          success: res => {
            // 获取到用户的 openid
            wx.setStorage({
              key: "openid",
              data: res.data.openid
            })
            wx.setStorage({
              key: "sessionkey",
              data: res.data.session_key
            })
            wx.setStorage({
              key: "unionid",
              data: res.data.unionid
            })
          }
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var _this = this
    _this.getcode()
    console.log(this.ifphone())
    _this.setData({
      ifphone: _this.ifphone(),
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: util.throttle(function () {
      var _this = this
      console.log(_this.data.current_page, _this.data.last_page)
      if (_this.data.current_page !== _this.data.last_page) {
        _this.setData({
          current_page: _this.data.current_page + 1,
          showflag: true,
          showfinish: false,
          
        })
      } else {
        _this.setData({
          showflag: false,
          showfinish: true,
        })
      }
      if (_this.data.showflag) {
        setTimeout(function () {
          wx.request({
            url: `${BASE_URL}/headline/list_data.html?page=${_this.data.current_page}&size=10&zhi=%E6%B4%BB%E5%8A%A8&type=xiaochengxv`,
            header: {
              'Content-Type': 'application/json', //GET方式是这个
            },
            method: "POST",
            success(res) {
              console.log(res)
              res.data.list.forEach(function (item, index) {
                item.info = JSON.parse(item.info)
                if (item.other_info) {
                  item.other_info = ''
                }
                var newDateTime = new Date().getTime() / 1000
                item.shijian = util.formatTime(item.info.shijian)
                if (Math.floor(newDateTime) > item.shijian) {
                  item.falg = false
                } else {
                  item.falg = true
                  _this.setData({
                    huodonglist: _this.data.huodonglist.concat(item),
                  })
                }
              })
              _this.setData({
                showflag: false,
              })
            }
          })
        }, 500)
      }
    },
    2000),


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var _this = this
    var userInfo = wx.getStorageSync('USER')
    var opid = wx.getStorageSync('openid')
    if (res.from === 'button') {}
    return {
      title: '想免费上课 , 求助力~',
      imageUrl: `${BASE_URL+_this.data.huodong.tuiimage}`,
      path: `views/huodongdetail/helpuserpage/index?dingdanid=${_this.data.id}&detailid=${_this.data.huodongid}&uid=${userInfo.id}&src=${userInfo.avatar}&opid=${opid}`,
      success: function (res) {
        console.log('成功', res)
      }
    }
  },


  //获取手机号
  getPhoneNumber: function (e) {
    var _this = this;
    _this.setData({
      popshow: false
    })
    wx.checkSession({
      success: function () {
        wx.request({
          url: `${BASE_URL}/ajax/getUserPhone`, //自己的解密地址
          data: {
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv,
            sessionKey: wx.getStorageSync("sessionkey")
          },
          method: "post",
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            if (e.detail.errMsg == "getPhoneNumber:ok") {
              wx.setStorage({
                key: "phoneNumber",
                data: res.data.phoneNumber
              })
              _this.setData({
                ifphone: false,
              })
              // 方式1：通过class名来获取所有的
              console.log(_this.data.id,
                res.data.phoneNumber, _this.data.active_list.tel == '')
              if (_this.data.active_list.tel == '') {
                wx.request({
                  url: `${BASE_URL}/ajax/phone`, //自己的解密地址
                  data: {
                    unionid: wx.getStorageSync('unionid'),
                    uid: _this.data.active_list.uid,
                    id: _this.data.id,
                    tel: res.data.phoneNumber,
                  },
                  method: "GET",
                  header: {
                    'content-type': 'application/json'
                  },
                  success: function (res) {
                    console.log(res, '提供手机号成功')
                  }
                })
              }
              // var phoneNumber = wx.getStorageSync('phoneNumber')
              // var opid = wx.getStorageSync('openid')
              // var unid = wx.getStorageSync('unionid')
              // var data = wx.getStorageSync('data')
              // wx.request({
              //   url: `${BASE_URL}/ajax/wechatinfo`, //仅为示例，并非真实的接口地址
              //   data: {
              //     avatarUrl: data.avatarUrl,
              //     city: data.avatarUrl,
              //     country: data.country,
              //     gender: data.gender,
              //     language: data.language,
              //     nickName: data.nickName,
              //     openId: opid,
              //     province: data.avatarUrl,
              //     unionId: unid,
              //     phonenumber: phoneNumber
              //   },
              //   method: "POST",
              //   header: {
              //     'content-type': 'application/json' // 默认值
              //   },
              //   success(res) {
              //     console.log(res, '授权手机号找到diy用户')
              //     wx.setStorage({
              //       key: "USER",
              //       data: res.data
              //     })
              //   }
              // })

            } else {
              wx.showToast({
                title: '请先登录哦',
                icon: 'none',
                duration: 2000
              })
            }
          }
        })
      },
      fail: function () {
        wx.request({
          url: `${BASE_URL}/ajax/getUserPhone`, //自己的解密地址
          data: {
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv,
            sessionKey: wx.getStorageSync("sessionkey")
          },
          method: "post",
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            if (e.detail.errMsg == "getPhoneNumber:ok") {
              wx.setStorage({
                key: "phoneNumber",
                data: res.data.phoneNumber
              })
              _this.setData({
                ifphone: false,
              })
              // 方式1：通过class名来获取所有的
              console.log(_this.data.id,
                res.data.phoneNumber)
              if (_this.data.active_list.tel == '') {
                wx.request({
                  url: `${BASE_URL}/ajax/phone`, //自己的解密地址
                  data: {
                    unionid: wx.getStorageSync('unionid'),
                    uid: _this.data.active_list.uid,
                    id: _this.data.id,
                    tel: res.data.phoneNumber,
                  },
                  method: "GET",
                  header: {
                    'content-type': 'application/json'
                  },
                  success: function (res) {
                    console.log(res, '提供手机号成功')
                  }
                })
              }
            } else {
              wx.showToast({
                title: '请先登录哦',
                icon: 'none',
                duration: 2000
              })
            }
          }
        })
      }
    })
  },
  //跳转文章详情页
  articleDetail: function (e) {
    var id = e.currentTarget.dataset.id
    wx.redirectTo({
      url: `/views/huodongdetail/index?id=${id}`
    })
  },
  //加入群聊
  completemessage: function (e) {
    // console.log(e)
    this.setData({
      popifshow: true,
    })
  },
  //我知道了
  iknow: function () {
    this.setData({
      popifshow: false
    })
  },


  //点击进群按钮的回调
  startmessage:function(){
    var _this=this
    console.log(11)
    wx.request({
      url: `${BASE_URL}/huodong/jinqun`, //自己的解密地址
      data: {
        id: _this.data.id,
      },
      method: "GET",
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res)
      }
    })
  }
})